/**
 * BomberBoy, CPS240 Term Project - Team A
 * Andrew Osterink, David Bash, Scott Kidder
 
 * This class is a singleton that manages the image
 * loading for the game. It either creates a new instance
 * of itself, or if an instance has already been created
 * it simply returns the previous instance. It has a method
 * to load an image that takes a String. If the String (key)
 * has been loaded before, it will return the Image
 * rather than loading the image again.
 *
 */
package pkg;

import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;

import javax.imageio.ImageIO;



/**
 * @author Scott Kidder
 *
 */
public class ResourceManager {

	private static ResourceManager manager;
	private HashMap<String, Image> sprites = new HashMap<String, Image>();
	protected ResourceManager() { /*Does nothing cannot be called by other classes*/ }
	
	public static ResourceManager getManager() {
		
		if(manager == null)
			manager = new ResourceManager();
		
		return manager;
	}
	/**
	 * @param key the url of the image we want to load eg "/img/redPlayer.gif"
	 * @return image an Image to be used in the Entity class
	 * 
	 */
	public Image load(String key) {
		
		if(sprites.get(key) != null)
			return (Image) sprites.get(key);
		
		BufferedImage newImg = null;
		
		URL url = this.getClass().getClassLoader().getResource(key);
		
		if(url == null)
			System.out.println("Could not lookup key:" + key);
		
		try {
			newImg = ImageIO.read(url);
		} catch (IOException e) {
			System.out.println("ImageIO failed at url:" + key);
		}
		
		GraphicsConfiguration config = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
		Image img = config.createCompatibleImage(newImg.getWidth(), newImg.getHeight(), Transparency.BITMASK);
		img.getGraphics().drawImage(newImg, 0, 0, null);
		sprites.put(key, img);
		
		return img;
	}
	
	
}
